/*
 * cryptomfs - a macfuse implementation of cryptofs.
 * Copyright (C) 2008  Greg J. Hedlund
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "AppController.h"
#import "NewFilesystemController.h"
#import "FSOps.h"

@implementation AppController

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)theApplication
{
	return NO;
}

- (BOOL)application:(NSApplication *)theApplication
	       openFile:(NSString *) filename
{
	[FSOps mountFilesystemAtPath:filename];

	NSUserDefaultsController * prefs = [NSUserDefaultsController sharedUserDefaultsController];
	id someVal = [[prefs values] valueForKey:@"closeAfterMount"];
	if(someVal != nil) {
		NSNumber * numVal = (NSNumber*)someVal;
		BOOL closeApp = [numVal boolValue];
		if(closeApp) {
			[[NSApplication sharedApplication] terminate:self];
		}
	}
	
	return YES;
}

- (IBAction)newFilesystem:(id)sender
{
	NewFilesystemController * controller =
		[[NewFilesystemController alloc] initWithWindowNibName:@"NewFilesystem"];
	// force window load
	[controller window];
	// show window
	[controller showWindow:self];
}

- (IBAction)openFilesystem:(id)sender
{
	// get the shared open panel instance
	NSOpenPanel* openPanel = [NSOpenPanel openPanel];
	[openPanel setAllowsMultipleSelection:NO];
	[openPanel setAllowedFileTypes:[NSArray arrayWithObject:@"cryptofs"]];
	[openPanel setCanChooseDirectories:NO];
	
	int retVal = [openPanel runModalForTypes:[NSArray arrayWithObject:@"cryptofs"]];
	
	if(retVal == NSOKButton) {
		NSString* filename = [[openPanel filenames] objectAtIndex:0];
		[FSOps mountFilesystemAtPath:filename];
	}
	
	NSUserDefaultsController * prefs = [NSUserDefaultsController sharedUserDefaultsController];
	id someVal = [[prefs values] valueForKey:@"closeAfterMount"];
	if(someVal != nil) {
		NSNumber * numVal = (NSNumber*)someVal;
		BOOL closeApp = [numVal boolValue];
		if(closeApp) {
			[[NSApplication sharedApplication] terminate:self];
		}
	}
}

@end
